const app = getApp()
import {
  list,
  find
} from '../../api/product'

import {
  add,
  buyNow,
  buyNowForGroupBuy
} from '../../api/cart'
const util = require('../../utils/util.js')
Component({
  data: {
    groupForm: {},
    giftCardId: '',
    productId: "", //已选中的商品id
    showConfirm: "", //控制底部按键
    type: "", //判断是不是购物车页面的属性点击进来的
    isClose: "", //控制是关闭弹窗还是跳转订单确认页面
    flag: false,
    wrapAnimate: 'wrapAnimate',
    bgOpacity: 0,
    frameAnimate: 'frameAnimate',
    spec1Off: false, //第一属性的开关
    spec2Off: false, //第一属性的开关
    imageSrc: "",
    imageList:[],
    point: "",
    types: '',
    imageSrcOrl: "",
    marketPrice: "", //市场价
    price: "", //销售价
    vipPrice: "", //会员价
    stock: "", //库存
    stockSum: 0, //总库存
    productState: true, //商品上下架状态
    minLimit: 1, //最小限购数量
    maxLimit: 0, //最大限购数量
    tagTextList: "", //显示所选的标签列表
    selectProduct: "", //被选中的商品
    currentNum: 1, //被选中的商品数量
    coupons: [], //优惠券
    promotions: [], //活动
    // spec1: "请选择配色分类", //第一属性
    // spec2: "请选择规格2", //第二属性
    //商品的属性列表
    attributeList: [],
    //测试的服务端数据
    tagControlList: [], //测试属性的控制列表
    origionalTagControlList: [],
    response: [],
    tabBarType: 0,
    product: {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //请求商品数据
    productInfoRequest(id) {
      var tabBarType = wx.getStorageSync('tabBarType')
      this.setData({
        tabBarType: tabBarType
      })
      wx.setStorageSync('tabBarType', 0)
      find(id).then(res => {
        if (res.type == 'success') {
          if (!res.data.products[0].isMarketable) {
            this.setData({
              productState: false
            })
          }
          this.data.response = res.data.products
          this.formateResponse(res.data.products)
          this.setData({
            flag: true,
            wrapAnimate: 'wrapAnimate',
            frameAnimate: 'frameAnimate',
            response:this.data.response
          })
          wx.hideLoading()
        }
      }
      ).catch(error => {
        console.log(error)
        wx.hideLoading()
        wx.showToast({
          title: '服务器开小差，请重试',
          icon: "none",
          duration: 1500
        })
      })
    },
    setNavSize: function () {
      var that = this,
        sysinfo = wx.getSystemInfoSync(),
        statusHeight = sysinfo.statusBarHeight,
        isiOS = sysinfo.system.indexOf('iOS') > -1,
        navHeight;
      if (!isiOS) {
        navHeight = 48;
      } else {
        navHeight = 44;
      }
      that.setData({
        windowHeight: sysinfo.windowHeight - statusHeight-navHeight//获取可用屏幕高度
      })
    },
    //显示底部弹窗
    showFrame(id, type, cardId) {
      this.setNavSize()
      if (!util.isNull(cardId)) {
        this.data.giftCardId = cardId
      }
      //阻止组件当前页面滑动
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })
      // console.log("显示底部弹窗id--" + JSON.stringify(id))
      // console.log("显示底部弹窗type--" + JSON.stringify(type))
      this.setData({
        productId: id,
      });
      this.productInfoRequest(id)
      if (type == "buyNow") { //立即购买过来的
        this.setData({
          showConfirm: true,
          isClose: false,
        });
      } else if (type == "addCart" || type == "changeAttr") { //点击加入购物车过来的
        this.setData({
          type: type,
          showConfirm: true,
          isClose: true,
        })
      } else if (type == "attribute") { //点击属性选择过来的
        this.setData({
          type: "addCart",
          showConfirm: false,
        })
      }
    },
    // 购买团购
    bounceGroup(id, data) {
      this.setData({
        groupForm: data,
        productId: id,
        type: "groupBuy",
      })
      this.productInfoRequest(id)
    },
    submitClick() {
      if (app.globalData.token == null) {
        wx.navigateTo({
          url: '/pages/login/index',
        })
      } else {
        let data = {
          productId: this.data.selectProduct.id,
          uuid: app.globalData.uuid,
          groupBuyId: this.data.groupForm.groupId,
          quantity: this.data.currentNum
        }
        // console.log(data)

        buyNowForGroupBuy(data).then(res => {
          // console.info("立即购买的请求--" + JSON.stringify(res))
          if (res.type == 'success') {
            let obj = {
              groupId: this.data.groupForm.groupId
            }
            wx.navigateTo({
              url: '/pages/goods/submit/index?groupId=' + data.groupBuyId,
            })
          }
        }
        ).catch(error => {
          wx.showToast({
            title: "服务器开小差了，请重新点击购买",
          })
        })
      }
    },
    //隐藏底部弹窗
    hideFrame() {
      this.setData({
        wrapAnimate: 'wrapAnimateOut',
        frameAnimate: 'frameAnimateOut'
      });
      //恢复组件当前页面滑动
      wx.setPageStyle({
        style: {
          overflow: ''
        }
      })
      setTimeout(() => {
        this.setData({
          flag: false
        })
      }, 400)
    },

    //属性标签的选择事件
    selectAttr: function (e) {
      let attrname = e.currentTarget.dataset.attrname
      let tagname = e.currentTarget.dataset.tagname
      let canSelected = e.currentTarget.dataset.canselected
      let isSelected = e.currentTarget.dataset.isselected
      if (canSelected) {
        this.control(attrname, tagname, canSelected, isSelected)
      }
    },

    //控制函数
    control(attrname, tagname, canSelected, isSelected) {
      let tagControlList = this.data.tagControlList
      let response = this.data.response

      let zeroStockList = [] //零库存列表
      let haveStockList = [] //非零库存列表
      if (response.length > 0) {
        response.map((item) => {
          if (tagname == item.spec1 || tagname == item.spec2) {
            if (item.stock > 0) {
              if (attrname == "规格1") {
                haveStockList.push(item.spec2)
              } else {
                haveStockList.push(item.spec1)
              }
            }
          }
        })
      }
      if (tagControlList.length > 0) {
        if (attrname == "规格1") {
          haveStockList.map((item) => {
            tagControlList.map((item1) => {
              if (item1.attrname == "规格2") {
                if (item1.tagname != item) {
                  zeroStockList.push(item1.tagname)
                }
              }
            })
          })
        } else {
          haveStockList.map((item) => {
            tagControlList.map((item1) => {
              if (item1.attrname == "规格1") {
                if (item1.tagname != item) {
                  zeroStockList.push(item1.tagname)
                }
              }
            })
          })
        }
      }
      let origionalTagControlList = this.data.origionalTagControlList
      if (tagControlList.length > 0) {
        tagControlList.map((item) => {
          if (isSelected) {
            if (item.tagname == tagname) {
              item.isSelected = false
            }
            if (item.attrname != attrname) {
              if (origionalTagControlList.length > 0) {
                origionalTagControlList.map((origionalTagControlListItem) => {
                  if (item.tagname == origionalTagControlListItem.tagname) {
                    item.canSelected = origionalTagControlListItem.canSelected
                  }
                })
              }

            }
          } else {
            if (item.attrname == attrname) {
              item.isSelected = false
            } else {
              if (zeroStockList.length > 0) {
                zeroStockList.map((zeroStockListItem) => {
                  if (zeroStockListItem == item.tagname) {
                    item.canSelected = false
                  }
                })
              }
              if (haveStockList.length > 0) {
                haveStockList.map((haveStockListItem) => {
                  if (haveStockListItem == item.tagname) {
                    item.canSelected = true
                  }
                })
              }
            }
            if (item.tagname == tagname) {
              item.isSelected = true
            }

          }

        })
      }
      let attributeList = this.data.attributeList
      // console.info("attributeList--" + JSON.stringify(attributeList))
      let spec1 = ""
      let spec2 = ""

      if (tagControlList.length > 0) {
        tagControlList.map((item) => {
          if (attributeList.length > 0) {
            attributeList.map((item1) => {
              if (item.attrname == item1.attrname) {
                if (item1.tagList.length > 0) {
                  item1.tagList.map((item2) => {
                    if (item.tagname == item2.tagname) {
                      item2.isSelected = item.isSelected
                      item2.canSelected = item.canSelected
                    }
                  })
                }
              }
              if (item.isSelected == true) {
                if (item.attrname == "规格1") {
                  spec1 = item.tagname
                } else {
                  spec2 = item.tagname
                }
              }
            })
          }
        })
      }
      let selectProduct = ""
      let tagTextList = this.data.tagTextList
      if (response.length > 0) {
        if (attributeList.length == 2) {
          response.map((item) => {
            if (item.spec2 == spec2 && item.spec1 == spec1) {
              selectProduct = item
            }
          })
          if (spec1 == "" && spec2 == "") {
            tagTextList = "请选择： 规格1，规格2"
            selectProduct = ""
          } else if (spec1 != "" && spec2 != "") {
            tagTextList = "已选：" + spec1 + "，" + spec2
          } else if (spec1 != "") {
            tagTextList = "请选择：规格2"
            selectProduct = ""
          } else {
            tagTextList = "请选择：规格1"
            selectProduct = ""
          }
        } else if (attributeList.length == 1) {
          if (spec1 == "") {
            response.map((item) => {
              if (item.spec2 == spec2) {
                selectProduct = item
              }
            })
            if (spec2 == "") {
              tagTextList = "请选择：规格2"
              selectProduct = ""
            } else {
              tagTextList = "已选：" + spec2
            }
          } else if (spec2 == "") {
            response.map((item) => {
              if (item.spec1 == spec1) {
                selectProduct = item
              }
            })
            if (spec1 == "") {
              tagTextList = "请选择：规格1"
              selectProduct = ""
            } else {
              tagTextList = "已选：" + spec1
            }
          }
        }
      }
      // console.info("selectProduct--" + JSON.stringify(selectProduct))
      if (selectProduct != "") {
        this.data.price = selectProduct.price
        this.data.vipPrice = selectProduct.vipPrice
        this.data.promotions = selectProduct.promotions
        this.data.types = selectProduct.type
        this.data.imageSrc = selectProduct.thumbnail
        if (selectProduct.maxLimit) {
          this.data.maxLimit = selectProduct.maxLimit
        }

        this.setData({
          currentNum: this.data.minLimit > 0 ? this.data.minLimit : this.data.currentNum,
          imageSrc: this.data.imageSrc,
          selectProduct: selectProduct, //被选中的商品
          attributeList: attributeList,
          marketPrice: this.data.marketPrice, //商品单价
          price: this.data.price, //商品单价
          stock: this.data.stock, //库存
          vipPrice: this.data.vipPrice,
          minLimit: this.data.minLimit, //限购数量
          tagTextList: tagTextList, //显示所选的标签列表
          coupons: this.data.coupons,
          promotions: this.data.promotions,
          maxLimit: this.data.maxLimit
        })

      }


    },

    //服务器数据整理
    formateResponse(res) {
      var _this = this
      let spec1List = []
      let spec2List = []
      let imageList = []
      let attributeList = []
      let stockSum = 0
      let spec1 = ""
      let spec2 = ""
      var imageSrcOrl = ""
      let productId = parseInt(this.data.productId)

      let tagTextList = ""

      if (res[0].spec1 != "" || res[0].spec2 != "") {
        tagTextList = "请选择："
      }
      if (res.length > 0) {
        res.map((item) => {
          imageList.push({url:item.thumbnail,specId:item.id})
          _this.setData({
            imageList:imageList
          })
          if (item.spec1) {
            spec1List.push(item.spec1)
            if (productId == item.id) {
              spec1 = item.spec1
            }
          }
          if (item.spec2) {
            spec2List.push(item.spec2)
            if (productId == item.id) {
              spec2 = item.spec2
            }
          }
          // priceList.push(item.price)
          stockSum += item.stock
          item
        })
        imageSrcOrl = util.thumbnail(res[0].thumbnail, 200, 200)
      }
      //去重
      if (spec1List.length > 0) {
        spec1List = Array.from(new Set(spec1List));
        tagTextList += "规格1"
        let attributeListItem = {}
        attributeListItem.attrname = "规格1"
        attributeListItem.tagList = []
        spec1List.map((item) => {
          let num = 0
          if (res.length > 0) {
            res.map((item1) => {
              if (item1.spec1 == item) {
                num += item1.stock
              }
            })
          }
          let tagListItem = {}
          if (num == 0) {
            tagListItem.canSelected = false
          } else if (num > 0) {
            tagListItem.canSelected = true
          }
          if (spec1 == item) {
            tagListItem.isSelected = true
          } else {
            tagListItem.isSelected = false
          }
          tagListItem.haveImage = false
          tagListItem.tagname = item
          attributeListItem.tagList.push(tagListItem)
        })
        attributeList.push(attributeListItem)
      }
      if (spec2List.length > 0) {
        spec2List = Array.from(new Set(spec2List));
        tagTextList += " 规格2"
        let attributeListItem = {}
        attributeListItem.attrname = "规格2"
        attributeListItem.tagList = []
        spec2List.map((item) => {
          let num = 0
          if (res.length > 0) {
            res.map((item1) => {
              if (item1.spec2 == item) {
                num += item1.stock
              }
            })
          }
          let tagListItem = {}
          if (num == 0) {
            tagListItem.canSelected = false
          } else if (num > 0) {
            tagListItem.canSelected = true
          }
          if (spec2 == item) {
            tagListItem.isSelected = true
          } else {
            tagListItem.isSelected = false
          }
          tagListItem.haveImage = false
          tagListItem.tagname = item
          attributeListItem.tagList.push(tagListItem)
        })
        attributeList.push(attributeListItem)
      }

      let tagControlList = []
      let origionalTagControlList = []
      if (attributeList.length > 0) {
        attributeList.map((item) => {
          if (item.tagList.length > 0) {
            item.tagList.map((item1) => {
              let tagControlListItem = {}
              tagControlListItem.attrname = item.attrname
              tagControlListItem.haveImage = item1.haveImage
              tagControlListItem.isSelected = item1.isSelected
              tagControlListItem.canSelected = item1.canSelected
              tagControlListItem.tagname = item1.tagname
              tagControlList.push(tagControlListItem)
              let origionalTagControlListItem = {}
              origionalTagControlListItem.attrname = item.attrname
              origionalTagControlListItem.haveImage = item1.haveImage
              origionalTagControlListItem.isSelected = item1.isSelected
              origionalTagControlListItem.canSelected = item1.canSelected
              origionalTagControlListItem.tagname = item1.tagname
              origionalTagControlList.push(origionalTagControlListItem)
            })
          }
        })
      }

      if (!util.isNull(res)) {
        var product = {}
        // res.forEach((item) =>{
        product = res[0]
        //   break;
        // })
        if (!util.isNull(product.promotions)) {
          product.promotions.forEach(function (item) {
            _this.data.promotions.push(item)
          })
        }
        this.setData({
          product: product,
          promotions: _this.data.promotions,
        })
      }
      this.data.price = product.price;
      this.data.vipPrice = product.vipPrice;
      this.data.marketPrice = product.marketPrice;
      this.setData({
        origionalTagControlList: origionalTagControlList,
        tagControlList: tagControlList,
        attributeList: attributeList,
        price: this.data.price,
        vipPrice: this.data.vipPrice,
        marketPrice: this.data.marketPrice,
        stockSum: stockSum,
        imageSrcOrl: imageSrcOrl,
        imageSrc: res[0].thumbnail,
        stock: stockSum,
        tagTextList: tagTextList, //显示所选的标签列表
      })
      if (!util.isNull(spec1)) {
        this.control("规格1", spec1, true, false)
      }
      if (!util.isNull(spec2)) {
        this.control("规格2", spec2, true, false)
      }
      if (util.isNull(spec1) && util.isNull(spec2)) {
        let response = this.data.response
        if (response.length > 0) {
          response.map(item => {
            if (item.id == productId) {
              this.data.selectProduct = item
              if (this.data.selectProduct.minLimit > 0) {
                this.setData({
                  currentNum: this.data.selectProduct.minLimit,
                  minLimit: this.data.selectProduct.minLimit
                })
              }
              if (this.data.selectProduct.minLimit > 0) {
                this.setData({
                  maxLimit: this.data.selectProduct.maxLimit
                })
              }
            }
          })
        }
      } else {
        this.data.selectProduct = product
        // console.log(product,'product');
        if (this.data.selectProduct.minLimit > 0) {
          this.setData({
            minLimit: this.data.selectProduct.minLimit,
            currentNum: this.data.selectProduct.minLimit > 0 ? this.data.selectProduct.minLimit : this.data.currentNum,
          })
        }
      }
    },
    //数量减少事件
    numReduce: function (e) {
      let selectProduct = this.data.selectProduct
      let currentNum = e.target.dataset.currentnum
      let minLimit = this.data.minLimit
      if (selectProduct) {
        let cartInfo = this.data.shopList
        // console.info("currentNum--" + currentNum)
        if (currentNum <= minLimit || currentNum <= 1) {
          wx.showToast({
            title: '商品数量不能再少了呦！',
            icon: 'none',
            duration: 1500
          })
        } else {
          currentNum--
          this.setData({
            currentNum: currentNum
          })
        }
      } else {
        wx.showToast({
          title: '请先选择商品属性呦！',
          icon: 'none',
          duration: 1500
        })
      }
    },

    //数量增加事件
    numAdd: function (e) {
      let selectProduct = this.data.selectProduct
      let currentNum = e.target.dataset.currentnum
      let maxLimit = 0
      // console.info("selectProduct.maxLimit--" + selectProduct.maxLimit)
      if (selectProduct.maxLimit) {
        maxLimit = selectProduct.maxLimit
      }
      // console.info("maxLimit--" + maxLimit)
      let stock = selectProduct.stock
      // console.info("selectProduct--" + JSON.stringify(selectProduct))
      if (selectProduct) {
        // console.info("maxLimit--" + maxLimit)
        if (maxLimit > 0) {
          if (currentNum >= maxLimit) {
            wx.showToast({
              title: '商品数量已达上限呦！',
              icon: 'none',
              duration: 1500
            })
          } else {
            currentNum++
            this.setData({
              currentNum: currentNum
            })
          }
        } else if (currentNum >= stock) {
          wx.showToast({
            title: '商品数量已达上限呦！',
            icon: 'none',
            duration: 1500
          })
        } else {
          // console.info("我进来了--" + maxLimit)
          currentNum++
          this.setData({
            currentNum: currentNum
          })
        }
        // }
      } else {
        wx.showToast({
          title: '请先选择商品属性呦！',
          icon: 'none',
          duration: 1500
        })
      }
    },

    //数量输入框的失焦事件
    bindblur: function (e) {
      let selectProduct = this.data.selectProduct
      let originalNum = this.data.currentNum
      let currentNum = e.detail.value
      let minLimit = selectProduct == '' ? 0 : parseInt(selectProduct.minLimit)
      let maxLimit = selectProduct == '' ? 0 : parseInt(selectProduct.maxLimit)
      // console.info("originalNum--" + originalNum)
      // console.info("currentNum--" + currentNum)
      // console.info("minLimit--" + minLimit)
      // console.info("maxLimit--" + maxLimit)
      // console.info("minLimit--" + typeof(minLimit))
      let stock = selectProduct == '' ? 0 : selectProduct.stock
      if (selectProduct) {
        if (currentNum < minLimit || currentNum < 1) {
          wx.showModal({
            title: '温馨提示',
            content: '商品数量不能小于下限呦！',
          })
          this.setData({
            currentNum: originalNum
          })
        } else if (maxLimit != 0) {
          if (currentNum > maxLimit) {
            wx.showModal({
              title: '温馨提示',
              content: '商品数量超过上限呦！',
            })
            this.setData({
              currentNum: originalNum
            })
          }
        } else if (currentNum > stock) {
          wx.showModal({
            title: '温馨提示',
            content: '商品数量超过上限呦！',
          })
          this.setData({
            currentNum: originalNum
          })
        } else {
          this.setData({
            currentNum: currentNum
          })
        }
      } else {
        wx.showToast({
          title: '请先选择商品属性呦！',
          icon: 'none',
          duration: 1500
        })
        this.setData({
          currentNum: originalNum
        })
      }
    },

    //检测用户的登陆状态
    checkLogin(callback) {
      // console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
      if (app.globalData.token == null) {
        wx.navigateTo({
          url: '/pages/login/index',
        })
      } else {
        if (callback) {
          callback()
        }
      }
    },

    //确定的提交事件
    submit() {
      let selectProduct = this.data.selectProduct
      let currentNum = this.data.currentNum
      // console.info("提交事件的selectProduct--" + JSON.stringify(selectProduct))
      this.checkLogin(() => {
        if (selectProduct) {
          if (this.data.stockSum > 0) {
            if (this.data.isClose) {
              this.addCartSubmit()
            } else {
              this.buySubmit()
            }
          }
        } else {
          wx.showToast({
            title: '请先选择商品属性呦！',
            icon: 'none',
            duration: 1500
          })
        }
      })
    },

    //加入购物车的按键事件
    addCartSubmit() {
      let _this = this
      this.checkLogin(() => {
        // console.info("加入购物车的按键事件")
        let selectProduct = this.data.selectProduct
        let currentNum = this.data.currentNum
        if (selectProduct) {
          //调用加入购物车的接口，成功后关闭弹窗
          if (this.data.stockSum > 0) {
            // console.info("this.data.type--" + this.data.type)

            if (this.data.type == "addCart") {
              //发送添加购物车的请求
              let data = {}
              data.productId = selectProduct.id
              data.promotionId = ""
              data.quantity = currentNum
              data.uuid = app.globalData.uuid
              // console.info("加入购物车的请求data--" + JSON.stringify(data))
              add(data).then(
                res => {

                  if (res.type == 'success') {
                    let info = {}
                    info.productId = selectProduct.id
                    info.currentNum = currentNum
                    info.spec = selectProduct.spec1 ? selectProduct.spec1 : '' + " " + selectProduct.spec2 ? selectProduct.spec2 : '',
                      info.price = selectProduct.price
                    this.triggerEvent("selectedInfo", info)

                    this.hideFrame()
                    wx.showToast({
                      title: '成功加入购物车',
                      duration: 2000
                    })

                    app.event.emit("onCartChange");
                  }
                }
              ).catch(error => {
                // console.log(error)
                this.hideFrame()
                wx.showToast({
                  title: error.content,
                  icon: 'none',
                  duration: 2000
                })
              })
            } else if (this.data.type == "changeAttr") {
              let info = {}
              info.productId = selectProduct.id
              info.currentNum = currentNum
              info.productInfo = selectProduct
              info.spec = selectProduct.spec1 ? selectProduct.spec1 : '' + " " + selectProduct.spec2 ? selectProduct.spec2 : '',
                this.triggerEvent("selectedInfo", info)
              this.hideFrame()
            }

          }
        } else {
          wx.showToast({
            title: '请先选择商品属性呦！',
            icon: 'none',
            duration: 1500
          })
        }
      })
    },

    //立即购买的按键事件
    buySubmit() {
      this.checkLogin(() => {
        let selectProduct = this.data.selectProduct
        let currentNum = this.data.currentNum
        if (selectProduct) {
          if (this.data.stockSum > 0) {
            let data = {}
            data.productId = selectProduct.id
            data.promotionId = ""
            data.quantity = currentNum
            data.uuid = app.globalData.uuid
            buyNow(data).then(
              res => {

                if (res.type == 'success') {
                  if (!util.isNull(this.data.giftCardId)) {
                    wx.navigateTo({
                      url: '/pages/goods/submit/index?id=' + this.data.giftCardId,
                      success: function (res) { },
                      fail: function (res) { },
                      complete: function (res) { },
                    })
                  } else {
                    wx.navigateTo({
                      url: '/pages/goods/submit/index',
                      success: function (res) { },
                      fail: function (res) { },
                      complete: function (res) { },
                    })
                  }

                  this.hideFrame()
                }
              }
            ).catch(error => {
              // console.log(error)
              this.hideFrame()
              wx.showToast({
                title: error.content,
                icon: 'none',
                duration: 2000
              })
            })
          }
        } else {
          wx.showToast({
            title: '请先选择商品属性呦！',
            icon: 'none',
            duration: 1500
          })
        }
      })
    },
    previewImage(e) {
      this.selectComponent("#previewComponent").showPreview();
    },
  }
})